package com.example.huixingzheng.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.huixingzheng.R;
import com.example.huixingzheng.dao.MQTTClient;
import com.example.huixingzheng.util.DBHelper;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;

public class WeatherFragment extends Fragment {

    private DBHelper dbHelper;
    private MQTTClient mqttClient;
    private WebView webView;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_weather, container, false);

        dbHelper = new DBHelper(requireContext());
        mqttConnect();

        webView = view.findViewById(R.id.webView);
        if (webView != null) {
            webView.setWebViewClient(new WebViewClient());
            webView.getSettings().setJavaScriptEnabled(true);
            String filePath = "file:///android_asset/sensor_data.html";
            webView.loadUrl(filePath);
        }

        return view;
    }

    private void mqttConnect() {
        String serverUri = "tcp://iot-06z00h2jsop1xez.mqtt.iothub.aliyuncs.com:1883";
        String clientId = "k13hseEeBlq.Device1|securemode=2,signmethod=hmacsha256,timestamp=1741703065179|";
        String username = "Device1&k13hseEeBlq";
        String password = "2322b8ed2e5f40385b5a70e25b0c225e74a5d69f0962a8ee9ae219ca4ac743a9";
        String topic = "/k13hseEeBlq/Device1/user/get";

        mqttClient = new MQTTClient(serverUri, clientId, username, password, topic, requireContext());
        mqttClient.connect();
        mqttClient.setCallback(new MqttCallbackHandler());
    }

    public class MqttCallbackHandler implements org.eclipse.paho.client.mqttv3.MqttCallback {
        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }

        @Override
        public void messageArrived(String topic, org.eclipse.paho.client.mqttv3.MqttMessage message) throws Exception {
            String messageContent = new String(message.getPayload());
            dbHelper.updateDataBasedOnMessage(messageContent);

            // 假设数据库中已保存最新的设备数据
            double temperature = dbHelper.getLatestTemperature();
            double humidity = dbHelper.getLatestHumidity();
            double smokeConcentration = dbHelper.getLatestSmokeConcentration();
            double lightLux = dbHelper.getLatestLightLux();

            // 使用 WebView 调用 JavaScript 更新数据
            String javascript = String.format("updateData(%f, %f, %f, %f);", temperature, humidity, smokeConcentration, lightLux);
            webView.evaluateJavascript(javascript, null);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            // 消息传递完成时的处理逻辑
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (webView != null) {
            webView.clearCache(true);
            webView.clearHistory();
            ViewGroup parent = (ViewGroup) webView.getParent();
            if (parent != null) {
                parent.removeView(webView);
            }
            webView.destroy();
            webView = null;
        }
    }
}
